<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <title>API explorer</title>
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/pearForm.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/fangge-style.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/pear-tree/dtree.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/nav.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/apiexplore.css}"/>
    <link rel="stylesheet" th:href="@{/admin/css/code.css}"/>
    <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>

<input type="hidden" name="resource" id="resource" th:value="${resource}">
<input type="hidden" name="name" id="apiName">
<input id="documentId" name="documentId" th:value="${documentId}" type="hidden"/>

<input type="hidden" name="projectId" id="projectId" th:value="${projectId}"/>
<div class="layui-fluid" style="margin-top: 10px">
    <div class="layui-row">
        <div class="layui-col-md8">
            <form class="layui-form layui-form-pane" action="" id="request_form">
                <fieldset class="layui-elem-field site-demo-button" style="margin-top: 10px;">
                    <div class="layui-form-item">
                        <div class="layui-input-inline">
                            <select id="method" name="method" lay-verify="method">
                                <option value="NON" disabled>请选择请求方式</option>
                                <option value="GET">GET</option>
                                <option value="POST">POST</option>
                                <option value="PUT">PUT</option>
                                <option value="DELETE">DELETE</option>
                                <option value="PATCH">PATCH</option>
                                <option value="OPTION">OPTION</option>
                            </select>
                        </div>
                        <div class="layui-input-inline">
                            <input id="url" type="text" name="url"
                                   placeholder="127.0.0.1:8080/springboot/{resource}/{id}"
                                   lay-verify="url" autocomplete="off"
                                   style="width: 220%"
                                   class="layui-input">
                        </div>
                        <button class="layui-btn" style="margin-left: 23%;float: left" lay-submit lay-filter="execute">
                            <i class="layui-icon layui-icon-triangle-r" style="font-size: 17px; color: white;"></i>调试
                        </button>
                        <button class="layui-btn" lay-submit lay-filter="save" id="saveDocBtn">
                            <i class="layui-icon layui-icon-email" style="font-size: 18px; color: white;"></i> 保存
                        </button>
                    </div>
                </fieldset>

                <div class="layui-collapse group">
                    <div class="layui-colla-item">
                        <!--layui-bg-red-->
                        <h2 class="layui-colla-title ">URI Path Variables</h2>
                        <div class="layui-colla-content" id="uri-fieldset">
                            <div class="layui-form-item" style="margin-top: 10px">
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn layui-btn-primary"
                                            id="add_pathvar_field_btn">
                                        增加参数
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-collapse group">
                    <div class="layui-colla-item">
                        <!--layui-bg-orange-->
                        <h2 class="layui-colla-title ">HTTP Request Headers</h2>
                        <div class="layui-colla-content" id="header-fieldset">
                            <div class="layui-form-item" style="margin-top: 10px">
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn layui-btn-primary"
                                            id="add_request_header_field">
                                        增加参数
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-collapse group">
                    <div class="layui-colla-item">
                        <h2 class="layui-colla-title ">HTTP Request Body</h2>
                        <div class="layui-colla-content" id="body-fieldset">
                            <div class="layui-form-item" style="margin-top: 10px">
                                <div class="layui-tab layui-tab-card ">
                                    <ul class="layui-tab-title">
                                        <li class="layui-this">
                                            <input type="radio" name="bodyTextType" value="JSON" title="JSON" checked>
                                        </li>
                                        <li><input type="radio" name="bodyTextType" value="XML" title="XML"></li>
                                    </ul>
                                    <div class="layui-tab-content">
                                        <div class="layui-tab-item layui-show">
                                               <textarea name="requestBodyTextType" id="request_body_json_text"
                                                         placeholder="请输入JSON"
                                                         class="layui-textarea" cols=20 rows=15></textarea>
                                        </div>
                                        <div class="layui-tab-item">
                                               <textarea name="requestBodyTextType" id="request_body_xml_text"
                                                         placeholder="请输入XML"
                                                         class="layui-textarea" cols=20 rows=15></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-collapse group">
                    <div class="layui-colla-item">
                        <!--layui-bg-red-->
                        <h2 class="layui-colla-title layui-bg-red ">HTTP Response Headers</h2>
                        <div class="layui-colla-content" id="response-header-field-fieldset">
                            <div class="layui-form-item" style="margin-top: 10px">
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn layui-btn-primary"
                                            id="response-header-field_btn">
                                        增加参数
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="layui-collapse group">
                    <div class="layui-colla-item">
                        <h2 class="layui-colla-title layui-bg-red ">HTTP Response Body</h2>
                        <div class="layui-colla-content" id="response-fieldset">
                            <div class="layui-form-item" style="margin-top: 10px">
                                <div class="layui-tab layui-tab-card ">
                                    <ul class="layui-tab-title">
                                        <li class="layui-this">
                                            <input type="radio" name="responseBodyTextType" value="JSON"
                                                   title="JSON" checked>
                                        </li>
                                        <li><input type="radio" name="responseBodyTextType" value="XML" title="XML">
                                        </li>
                                    </ul>
                                    <div class="layui-tab-content">
                                        <div class="layui-tab-item layui-show">
                                               <textarea name="responseBodyTextType" id="response_body_json_text"
                                                         placeholder="请输入JSON"
                                                         class="layui-textarea" cols=20 rows=15></textarea>
                                        </div>
                                        <div class="layui-tab-item">
                                               <textarea name="responseBodyTextType" id="response_body_xml_text"
                                                         placeholder="请输入XML"
                                                         class="layui-textarea" cols=20 rows=15></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-col-md4" id="testLogDiv" style="display: none">
            <div class="layui-row" style="text-align: center">
                调试记录
            </div>
            <div class="layui-row">
                <table id="testLogTable" lay-filter="testLogTable"></table>
            </div>
        </div>
    </div>
</div>

<div id="testMode" style="display: none">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">模式选择</label>
            <div class="layui-input-block">
                <input type="radio" name="executeMode" value="out" title="外网调试" checked>
                <input type="radio" name="executeMode" value="rpc" title="RPC远程调试">
            </div>
        </div>
    </form>
</div>

<div id="consolePage" class="layui-fluid" style="display: none;width: 400px">
</div>
<script type="text/html" id="testLogTableToolbar">
    <div class="layui-btn-container">
        <button title="导入历史数据" class="layui-btn layui-btn-sm layui-btn-primary" lay-event="export">
            <i class="layui-icon layui-icon-export" style="font-size: 20px; color: black;"></i>
        </button>
        <button title="详情" class="layui-btn layui-btn-sm layui-btn-primary" lay-event="detail">
            <i class="layui-icon layui-icon-file" style="font-size: 20px; color: black;"></i>
        </button>
        <button title="刷新数据" class="layui-btn  layui-btn-primary layui-btn-sm" lay-event="refresh">
            <i class="layui-icon layui-icon-refresh" style="font-size: 20px; color: black;"></i>
        </button>
        <button title="删除" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="del" id="deleteTestLogBtn">
            <i class="layui-icon layui-icon-delete" style="font-size: 20px; color: black;"></i>
        </button>
    </div>
</script>
<script th:src="@{/layui/layui.js}"></script>
<script th:src="@{/admin/js/jquery.js}"></script>
<script th:src="@{/admin/js/doc/response.js}"></script>
<script th:src="@{/admin/js/doc/urivar.js}"></script>
<script th:src="@{/admin/js/doc/header.js}"></script>
<script th:src="@{/admin/js/doc/content.js}"></script>
<script th:src="@{/admin/js/doc/response_header.js}"></script>
<script th:src="@{/admin/js/marked.min.js}" type="application/javascript" charset="UTF-8"></script>
<script th:src="@{/admin/js/util.js}"></script>
<script type="text/javascript" th:inline="javascript">
    $("#projectNav").addClass("layui-this");
    var msg;
    var globalExecuteResult = null;
    var readOnly = parent.readOnly;

    if (readOnly !== null) {
        $('#saveDocBtn,#deleteTestLogBtn').css('display', 'none')
    }

    var tipTool = null;
    layui.config({
        base: '/restdoc/layui/lay/extends/'
    }).use(['layer',
        'form',
        'element',
        'jquery',
        'table',
        'yutons_sug'
    ], function () {

        var form = layui.form;
        var $ = layui.jquery;
        msg = layui.layer;
        var layer = layui.layer;
        var element = layui.element;
        var table = layui.table;
        var yutons_sug = layui.yutons_sug;
        tipTool = yutons_sug;

        var treeData = null;
        var documentId = $("#documentId").val();

        $.ajax({
            type: 'GET',
            url: '/restdoc/' + $("#projectId").val() + '/resource/tree?onlyResource=true',
            async: false,
            success: function (data) {
                if (data['code'] === "200") {
                    treeData = data['data'];
                } else {
                    layer.msg(data['message']);
                }
            },
            error: function () {
                layer.msg("网络异常");
            }
        });
        form.verify({
            url: function (value, item) {
                if (value === "") return "URL格式不正确";
            },
            type: function (value, item) {
                if (value === "NON")
                    return "请选择参数类型";
            },
            uriValue: function (value, item) {
                if (value === "") return "uri变量必填";
            },
            pass: []
        });

        //第一个实例
        if (documentId != null && documentId !== "") {
            $("#testLogDiv").css("display", "block");
            table.render({
                elem: '#testLogTable'
                , id: "testLogTable"
                , url: '/restdoc/document/' + documentId + '/httpapitestlog/page'
                , page: true
                , toolbar: '#testLogTableToolbar'
                , size: 'sm'
                , skin: 'nob'
                , limit: '50'
                , limits: [50, 100]
                , totalRow: false
                , loading: true
                , title: '调试记录'
                , defaultToolbar: []
                , text: {
                    none: '无调试记录'
                }
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},

                        {
                            width: 60, field: 'success', title: '状态', align: 'center', templet: function (res) {
                                if (res.success) {
                                    return "<i class='layui-icon layui-icon-ok-circle' style='=font-size: 17px; color: #5FB878;'></i>"
                                } else {
                                    return "<i class='layui-icon layui-icon-close-fill' style='=font-size: 17px; color: #FF5722;'></i>"
                                }
                            }
                        },
                        {field: 'testMode', title: '模式', align: 'center', width: 100},
                        {field: 'remote', title: '地址', align: 'center'}/*,
                        {
                            field: 'createTime',
                            title: '时间',
                            align: 'center',
                            templet: '<label>{{formatTimestamp(d.createTime)}}</label>'
                        }*//*,
                        {fixed: 'right', title: '操作', align: 'center', toolbar: "#testLogOperate"}*/
                    ]
                ]
            });

            table.on('toolbar(testLogTable)', function (obj) {
                var checkStatus = table.checkStatus(obj.config.id);
                switch (obj.event) {
                    case 'export':
                        var data = checkStatus.data;
                        if (data.length !== 1) {
                            layer.alert("导入测试数据只能选择一条测试记录");
                        } else if (data.length === 1) {
                            clearURIParamInput();
                            clearRequestHeaderParamInput();
                            clearResponseHeaderParamInput();
                            $.ajax({
                                method: "POST",
                                url: "/restdoc/document/httpapitestlog/" + data[0].id + "/deProject",
                                aysnc: false,
                                success: function (res) {
                                    initTestApiDoc(res['data'], document, form);
                                    element.render('collapse');
                                },
                                error: function () {
                                    layer.msg("Error");
                                }
                            });
                        } else {
                            layer.msg('无数据可导入');
                        }
                        break;
                    case 'del':
                        var data = checkStatus.data;
                        var ids = [];
                        for (var i = 0; i < data.length; i++) ids.push(data[i].id);
                        if (ids.length == 0) layer.msg('无数据可删除');
                        $.ajax({
                            method: "DELETE",
                            url: "/restdoc/document/httpapitestlog/batch",
                            data: JSON.stringify({ids: ids}),
                            contentType: 'application/json; charset=utf-8',
                            aysnc: false,
                            success: function (res) {
                                if (res.code === '200') {
                                    refreshTestLogTable();
                                    layer.msg("删除成功");
                                } else {
                                    layer.msg(res.message)
                                }
                            },
                            error: function () {
                                layer.msg("Error");
                            }
                        });
                        break;
                    case 'refresh':
                        refreshTestLogTable();
                        break;
                    case 'detail':
                        var data = checkStatus.data;
                        var ids = [];
                        for (var i = 0; i < data.length; i++) ids.push(data[i].id);
                        if (ids.length != 1) layer.msg('请选择一条记录');
                        else {
                            $.ajax({
                                method: "POST",
                                url: "/restdoc/document/httpapitestlog/" + ids[0] + "/log2testresult",
                                contentType: 'application/json; charset=utf-8',
                                aysnc: false,
                                success: function (res) {
                                    if (res.code === '200') {
                                        openConsolePage(res.data);
                                    } else {
                                        layer.msg(res.message);
                                    }
                                },
                                error: function () {
                                    layer.msg("Error");
                                }
                            });
                        }
                        break;
                }
            });
        }

        function refreshTestLogTable() {
            table.reload('testLogTable', {
                url: '/restdoc/document/' + documentId + '/httpapitestlog/page'
            });
        }

        $('#tableContent').click(function () {
            layer.open({
                type: 1,
                title: '选择目录',
                content: $('#sourceTreeDiv'),
                area: ['300px', '400px']
            });
        });

        $("#add_request_header_field").click(function (event) {
            $("#header-fieldset").append(getNewHeaderLine());
            form.render();
        });

        function addRequestParamInput() {
            $("#body-fieldset").append(oneline);
        }

        function addResponseParamInput() {
            $("#response-fieldset").append(responseoneline);
        }

        function clearURIParamInput() {
            var all_input_line = $("#uri-fieldset").children(".one-uri-header-line");
            cleanInputLine(all_input_line);
        }

        function clearRequestHeaderParamInput() {
            var all_input_line = $("#header-fieldset").children(".one-request-header-line");
            cleanInputLine(all_input_line);
        }

        function clearResponseHeaderParamInput() {
            var all_input_line = $("#response-header-field-fieldset").children(".one_response_header_line");
            cleanInputLine(all_input_line);
        }

        function clearQueryParamParamInput() {
            var all_input_line = $("#query-param-string-field-fieldset").children(".one-query-param-string-line");
            cleanInputLine(all_input_line);
        }

        function cleanInputLine(all_input_line) {
            var line_length = all_input_line.length;
            if (line_length > 0) {
                for (let i = 0; i < line_length; i++) {
                    var obj = all_input_line[i];
                    var parent = obj.parentNode;
                    parent.removeChild(obj)
                }
            }
        }

        $("#response-header-field_btn").click(function (event) {
            $("#response-header-field-fieldset").append(one_response_header_line);
            form.render();
        });

        $("#add_pathvar_field_btn").click(function (event) {
            $("#uri-fieldset").append(oneuriline);
            form.render();
        });

        form.on('submit(save)', function (data) {
            var projectId = $("#projectId").val();
            var map = getFormData(data.field);

            map['executeResult'] = globalExecuteResult;
            var method;
            var did = $("#documentId").val();

            map["projectId"] = projectId;
            map["documentId"] = did;
            var isNewDoc = true;
            if (did === undefined || did === "") {
                method = "POST"
            } else {
                method = "PUT";
                isNewDoc = false;
            }

            if (isNewDoc) {
                layer.open({
                    type: 2,
                    title: '完善API基本信息',
                    area: ['700px', '500px'],
                    content: ['/restdoc/' + projectId + '/document/baseinfo/edit/view', 'no'],
                    btn: ['确定', '取消'],
                    yes: function (index, doc) {
                        var res = window["layui-layer-iframe" + index].getFormData();

                        map['name'] = res['name'];
                        map['resource'] = res['resource'];

                        $("#apiName").val(res['name']);
                        $("#resource").val(res['resource']);

                        $.ajax({
                            type: 'POST',
                            dataType: 'JSON',
                            contentType: 'application/json;charset=utf-8',
                            url: '/restdoc/document',
                            data: JSON.stringify(map),
                            async: false,
                            success: function (data) {
                                if (data['code'] === "200") {
                                    if (data['data'] != null) {
                                        var id = data['data'];
                                        $('#documentId').val(id);
                                        console.info(id);
                                        layer.msg("保存成功");
                                    } else {
                                        layer.msg("保存失败")
                                    }
                                } else {
                                    layer.msg(data['message'])
                                }
                            },
                            error: function () {
                                layer.msg("网络异常")
                            }
                        });
                        layer.close(index);
                    }
                });
            } else {
                map['name'] = $("#apiName").val();
                map['resource'] = $("#resource").val();

                $.ajax({
                    type: 'PUT',
                    dataType: 'JSON',
                    contentType: 'application/json;charset=utf-8',
                    url: '/restdoc/document',
                    data: JSON.stringify(map),
                    async: false,
                    success: function (data) {
                        if (data['code'] === "200") {
                            if (data['data'] != null) {
                                var id = data['data'];
                                $('#documentId').val(id);
                                layer.msg("保存成功");
                            } else {
                                layer.msg("保存失败")
                            }
                        } else {
                            layer.msg(data['message'])
                        }
                    },
                    error: function () {
                        layer.msg("网络异常")
                    }
                });
            }
            return false;
        });

        form.on('submit(execute)', function (data) {
            var map = getFormData(data.field);
            layer.open({
                type: 1,
                content: $('#testMode'),
                title: '调试模式选择',
                btn: ['确定', '取消'],
                area: ['300px', '200px'],
                yes: function (index, layero) {
                    if ("out" === $("input[name='executeMode']:checked").val()) {
                        publicNetExecute(map);
                    } else {
                        rpcExecute(map);
                    }
                    layer.close(index);
                }
            });
            return false;
        });

        function rpcExecute(map) {
            layer.open({
                type: 2,
                title: '请选择运行服务实例',
                content: '/restdoc/serviceClient/view/list',
                area: ['600px', '400px'],
                btn: ['确定', '取消'],
                yes: function (index, dom) {
                    var res = window["layui-layer-iframe" + index].getCheckData();
                    map["executeMode"] = "remoteAddress";
                    map["remoteAddress"] = res[0]['remoteAddress'];
                    map['projectId'] = $("#projectId").val();
                    map["documentId"] = $("#documentId").val();

                    $.ajax({
                        type: 'POST',
                        dataType: 'JSON',
                        contentType: 'application/json;charset=utf-8',
                        url: '/restdoc/httptask/submit',
                        data: JSON.stringify(map),
                        async: false,
                        success: function (data) {
                            if (data['code'] === "200") {
                                executeResult = data['data'];
                                layer.msg('执行成功')
                            } else {
                                layer.msg(data['message']);
                            }
                        },
                        error: function () {
                            layer.msg("网络异常")
                        }
                    });

                    if (executeResult != null) {
                        globalExecuteResult = executeResult;
                        var invocationResult = executeResult;
                        if (invocationResult != null) {
                            openConsolePage(invocationResult)
                        }
                    }
                    layer.close(index)
                }
            });
        }

        function publicNetExecute(map) {
            if (!/^https?:\/\/.+/.test(map['url'])) {
                layer.msg("请填写完整的URL地址，缺少IP地址端口或者域名")
            } else {
                map['projectId'] = $("#projectId").val();
                map["documentId"] = $("#documentId").val();

                $.ajax({
                    type: 'POST',
                    dataType: 'JSON',
                    contentType: 'application/json;charset=utf-8',
                    url: '/restdoc/httptask/submit',
                    data: JSON.stringify(map),
                    async: false,
                    success: function (data) {
                        if (data['code'] === "200") {
                            if (data['data'] != null) {
                                executeResult = data['data'];
                                layer.msg('执行成功')
                            } else {
                                layer.msg("任务提交失败")
                            }
                        } else {
                            layer.msg(data['message'])
                        }

                    },
                    error: function () {
                        layer.msg("网络异常")
                    }
                });

                if (executeResult != null) {
                    globalExecuteResult = executeResult;
                    var invocationResult = executeResult;

                    if (invocationResult != null) {
                        if (invocationResult['responseBody'] != null) {
                            openConsolePage(invocationResult)
                        }
                    }
                }
            }
        }

        function completeExecuteCallback(queryParam, header, body) {
            if (body != null) {
                initResponseBody(body);
            }
            if (header !== null) {
                clearResponseHeaderParamInput();
                initResponseHeaderField(header);
            }
            element.render('collapse');
            refreshTestLogTable();
        }

        function openConsolePage(data) {
            var start = "<div class='layui-collapse'>";
            var end = "</div>";

            // General
            start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>General</h2>" +
                "<div class='layui-colla-content layui-show'><strong>Status Code:&nbsp;&nbsp;&nbsp;</strong>" + data.status +
                "<br><strong>Request URL:&nbsp;&nbsp;&nbsp;</strong>" + data.invocation.url +
                "<br><strong>Request Method:&nbsp;&nbsp;&nbsp;</strong>" + data.invocation.method +
                "</div></div>";

            // RequestHeader
            var requestHeaderH5Text = "";
            if (data.invocation.requestHeaders != null) {
                for (const [key, value] of Object.entries(data.invocation.requestHeaders)) {
                    requestHeaderH5Text = requestHeaderH5Text + "<strong>" + key + "&nbsp;&nbsp;&nbsp;</strong>" + value + "<br>";
                }
                if (requestHeaderH5Text !== '') {
                    start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>Request Headers</h2>" +
                        "<div class='layui-colla-content'>" + requestHeaderH5Text + "</div></div>";
                }
            }

            if (data.invocation.uriVariable != null) {
                // URI var
                var uriVarH5Text = "";
                for (const [key, value] of Object.entries(data.invocation.uriVariable)) {
                    uriVarH5Text = uriVarH5Text + "<strong>" + key + "&nbsp;&nbsp;&nbsp;</strong>" + value + "<br>";
                }
                if (uriVarH5Text !== '') {
                    start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>URI Variable</h2>" +
                        "<div class='layui-colla-content'>" + uriVarH5Text + "</div></div>";
                }
            }

            // Query Param
            if (data.queryParam != null) {
                var queryParamH5Text = "";
                for (const [key, value] of Object.entries(data.queryParam)) {
                    queryParamH5Text = queryParamH5Text + "<strong>" + key + "&nbsp;&nbsp;&nbsp;=</strong>" + value + "<br>";
                }
                if (queryParamH5Text !== '') {
                    start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>Query Param</h2>" +
                        "<div class='layui-colla-content'>" + queryParamH5Text + "</div></div>";
                }
            }
            // RequestBody
            if (data.invocation.requestBody != null) {
                var requestBodyH5Text = "";
                for (const [key, value] of Object.entries(data.invocation.requestBody)) {
                    requestBodyH5Text = requestBodyH5Text + "<strong>" + key + "&nbsp;&nbsp;&nbsp;</strong>" + value + "<br>";
                }
                if (requestBodyH5Text !== '') {
                    start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>Request Body</h2>" +
                        "<div class='layui-colla-content'>" + requestBodyH5Text + "</div></div>";
                }
            }

            // ResponseHeader
            var responseHeadersH5Text = "";
            if (data.responseHeaders != null) {
                for (const [key, value] of Object.entries(data.responseHeaders)) {
                    responseHeadersH5Text = responseHeadersH5Text + "<strong>" + key + "&nbsp;&nbsp;&nbsp;</strong>" + value + "<br>";
                }
            }
            start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>Response Headers</h2>" +
                "<div class='layui-colla-content'>" + responseHeadersH5Text + "</div></div>";

            // ResponseBody
            var responseBodyH5Text = "";
            if (data.responseBody != null) {
                var isJSON = false;
                var isXML = false;
                for (let i = 0; i < data.responseHeaders['Content-Type'].length; i++) {
                    if (data.responseHeaders['Content-Type'][i].includes('json')) {
                        isJSON = true;
                    } else if (data.responseHeaders['Content-Type'][i].includes('xml')) {
                        isXML = true;
                    }
                }
                if (isJSON) {
                    responseBodyH5Text = responseBodyH5Text + "<pre>" + formatJson(JSON.stringify(data.responseBody)) + "</pre>";
                } else {
                    responseBodyH5Text = responseBodyH5Text + "<pre style='font-size: 17px'>" + data.responseBody + "</pre>";
                }
            }

            start = start + "  <div class='layui-colla-item'><h2 class='layui-colla-title'>Response Body</h2>" +
                "<div class='layui-colla-content'>" + responseBodyH5Text + "</div></div>";
            $('#consolePage').html(start + end);
            element.render('collapse');

            layer.open({
                type: 1,
                title: '测试结果',
                content: $('#consolePage'),
                area: ['600px', '500px'],
                btn: ['导入数据', '取消'],
                yes: function (index, doc) {
                    completeExecuteCallback(data.queryParam, data.responseHeaders, data.responseBody);
                    layer.close(index);
                }
            });
        }

        function getFormData(value) {
            var header = getHeaderKeyValueJsonArray();
            var requestFields = getRequestBodyText();
            var responseFields = getResponseBodyText();
            var uriFields = getUriVarJsonArray();
            var responseHeader = getResponseHeaderKeyValueJsonArray();

            var map = new Map();

            map['url'] = value["url"];
            map['name'] = value['name'];
            map['description'] = value['description'];
            map['resource'] = value['resource'];
            map['method'] = value["method"];
            map['headers'] = header;
            map['requestFields'] = requestFields;
            map['responseFields'] = responseFields;
            map['uriFields'] = uriFields;
            map['responseHeaders'] = responseHeader;

            return map;
        }

        function getHeaderKeyValueJsonArray() {
            var headerKeyNodes = $('input[name=headerKey]');
            var headerValueNodes = $('input[name=headerValue]');
            var headerConstraintNodes = $('input[name=headerConstraint]');

            var array = [];

            for (let i = 0; i < headerKeyNodes.length; i++) {
                var map = new Map();
                map["headerKey"] = headerKeyNodes[i].value;
                map["headerValue"] = headerValueNodes[i].value;
                map["headerConstraint"] = (headerConstraintNodes[i].value === 'on');

                array[i] = map
            }
            return array
        }

        function getResponseHeaderKeyValueJsonArray() {
            var headerKeyNodes = $('input[name=responseHeaderField]');
            var headerValueNodes = $('input[name=responseHeaderValue]');
            var map = new Map();
            for (let i = 0; i < headerKeyNodes.length; i++) {
                map[headerKeyNodes[i].value] = headerValueNodes[i].value;
            }
            return map;
        }

        function getRequestBodyText() {
            var checkedValue = $("input[name='responseBodyTextType']:checked").val();
            if (checkedValue === "JSON") {
                var jsonText = $("#response_body_json_text").val();
                if (jsonText === "") return null;
                return JSON.parse(jsonText);
            } else {
                var jsonValue = null;
                var xmlText = $("#response_body_xml_text").val();
                if (xmlText === "") return jsonValue;
                $.ajax({
                    url: '/restdoc/textprotocol/xml2Json',
                    method: 'POST',
                    async: false,
                    contentType: "application/json",
                    data: JSON.stringify({
                        'text': xmlText
                    }),
                    success: function (res) {
                        if (res.code === '200') {
                            jsonValue = JSON.parse(res.data);
                        } else {
                            layer.msg(res.message);
                        }
                    }
                });
                return jsonValue;
            }
        }

        function getResponseBodyText() {
            var checkedValue = $("input[name='responseBodyTextType']:checked").val();
            if (checkedValue === "JSON") {
                try {
                    return JSON.parse($("#request_body_json_text").val());
                } catch (error) {
                    console.info(error);
                    return null;
                }

            } else {
                var jsonValue = null;
                var xmlText = $("#request_body_xml_text").val();
                if (xmlText == "") return null;
                $.ajax({
                    url: '/restdoc/textprotocol/xml2Json',
                    method: 'POST',
                    async: false,
                    contentType: "application/json",
                    data: JSON.stringify({
                        'text': xmlText
                    }),
                    success: function (res) {
                        if (res.code === '200') {
                            jsonValue = JSON.parse(res.data);
                        } else {
                            layer.msg(res.message);
                        }
                    }
                });
                return jsonValue;
            }
        }

        function beforeTestCheckUriVars(array) {
            for (var i = 0; i < array.length; i++) {
                if (array[i]['field'] !== null && array[i]['field'] !== "" && array[i]['value'] === "") {
                    return array[i]['field'];
                }
            }
            return null;
        }

        function getUriVarJsonArray() {
            var uriFields = $('input[name=uriField]');
            var uriValueFields = $('input[name=uriValue]');
            var array = new Array();
            for (let i = 0; i < uriFields.length; i++) {
                var map = new Map();
                map['field'] = uriFields[i].value;
                map['value'] = uriValueFields[i].value;
                array[i] = map;
            }
            return array
        }

        var document = [[${initDocument}]];
        if (document !== null) {
            initBaseInput(document);
            element.render('collapse');
        }
    });

    function deleteResponseBodyBtn(obj) {
        var parent = obj.parentNode.parentNode.parentNode;
        var children = obj.parentNode.parentNode;
        parent.removeChild(children);
    }

    function deleteRequestBodyBtn(obj) {
        var parent = obj.parentNode.parentNode.parentNode;
        var children = obj.parentNode.parentNode;
        parent.removeChild(children);
    }

    function deleteHeaderFieldLine(obj) {
        var parent = obj.parentNode.parentNode.parentNode;
        var children = obj.parentNode.parentNode;
        parent.removeChild(children)
    }

    function deleteUriVarFieldLine(obj) {
        var parent = obj.parentNode.parentNode.parentNode;
        var children = obj.parentNode.parentNode;
        parent.removeChild(children);
    }

    function deleteResponseHeaderFieldLine(obj) {
        var parent = obj.parentNode.parentNode.parentNode;
        var children = obj.parentNode.parentNode;
        parent.removeChild(children);
    }

    function tipHeaderKey(id) {
        var searchURL = "/restdoc/httpstandard/helper/headerkey/search?text=";
        tipTool.render({
            id: id,
            type: 'sug',
            url: searchURL,
            field: "headerKey"
        });
    }

    function tipHeaderValue(keyId, valueId) {
        var searchURL = "/restdoc/httpstandard/helper/headerValue/search?headerKey=" + $("#" + keyId).val() + "&text=";
        tipTool.render({
            id: valueId,
            type: 'sug',
            url: searchURL,
            field: "headerValue"
        });
    }

</script>
</body>
</html>